package cn.com.acca.ma.dao.impl;

import cn.com.acca.ma.dao.StockTransactionDataAllDao;
import cn.com.acca.ma.dao.StockTransactionDataDao;
import cn.com.acca.ma.jpa.util.JpaUtil;
import javax.persistence.EntityManager;
import javax.persistence.Query;

public class StockTransactionDataAllDaoImpl extends BaseDaoImpl<StockTransactionDataAllDaoImpl> implements
    StockTransactionDataAllDao {

    public StockTransactionDataAllDaoImpl() {
        super();
    }

    /**
     * 根据开始日期和结束日期，从表stock_transaction_data向表stock_transaction_data_all中写数据
     * @param multithreading
     * @param beginDate
     * @param endDate
     */
    public void writeStockTransactionDataAllByDate(boolean multithreading, String beginDate, String endDate) {
        logger.info("根据开始日期【" + beginDate + "】和结束日期【" + endDate + "】，"
            + "从表stock_transaction_data向表stock_transaction_data_all中写数据");

        EntityManager entityManager = null;
        Query query;
        if (multithreading) {
            entityManager = JpaUtil.newEntityManager();
            entityManager.getTransaction().begin();
            query = entityManager.createNativeQuery("insert into stock_transaction_data_all "
                + "select * from stock_transaction_data t "
                + "where t.date_ between to_date(?, 'yyyy-mm-dd') and to_date(?, 'yyyy-mm-dd')");
        } else {
            em = JpaUtil.currentEntityManager();
            em.getTransaction().begin();
            query = em.createNativeQuery("insert into stock_transaction_data_all "
                + "select * from stock_transaction_data t "
                + "where t.date_ between to_date(?, 'yyyy-mm-dd') and to_date(?, 'yyyy-mm-dd')");
        }

        query.setParameter(1, beginDate);
        query.setParameter(2, endDate);
        query.executeUpdate();

        if (multithreading) {
            entityManager.getTransaction().commit();
            entityManager.close();
        } else {
            em.getTransaction().commit();
            em.close();
        }
    }

    /**
     * 删除stock_transaction_data_all表中，开始时间和结束时间之间的记录
     * @param beginDate
     * @param endDate
     */
    @Override
    public void deleteWithDate(String beginDate, String endDate) {
        logger.info("删除stock_transaction_data_all表中，开始时间【" + beginDate + "】和结束时间【" + endDate + "】之间的记录");

        em = JpaUtil.currentEntityManager();
        em.getTransaction().begin();
        Query query = em.createNativeQuery("delete from stock_transaction_data_all t "
                + "where t.date_ between to_date(?, 'yyyy-mm-dd') and to_date(?, 'yyyy-mm-dd')");
        query.setParameter(1, beginDate);
        query.setParameter(2, endDate);
        query.executeUpdate();
        em.getTransaction().commit();
        em.close();
    }
}
